import { Application, Context } from "egg";

// 设备验签
module.exports = () => {
  return async (ctx: Context, next) => {
    try {
      const rule = {
        // appId: { type: "string", required: true },
        timestamp: { type: "string", signType: true },
        sign: { type: "string", required: true },
        method: { type: "string", required: true },
        bizContent: { type: "string", required: true },
      };

      const validateErrorList = ctx.app.validator.validate(rule, ctx.request.body);

      if (validateErrorList?.length) {
        throw new Error(`${validateErrorList[0].field}参数丢失`);
      }
    } catch (error) {
      ctx.status = 400;
      ctx.body = {
        code: 501,
        msg: error.message,
      };
      return;
    }

    try {
      const params = ctx.request.body;

      const { SECRET } = ctx.app.config.jwt;

      const validSign = ctx.service.utils.payUtils.verifySign(params, SECRET);
      if (!validSign) {
        throw new Error("签名错误");
      }

      await next();
    } catch (e) {
      // ctx.logger.error("验签失败:" + e.message);
      ctx.status = 400;
      ctx.body = {
        code: 502,
        msg: e.message,
      };
    }
  };
};
